package com.qk.management.aspect;

import cn.hutool.json.JSONUtil;
import com.qk.code.BusinessEnum;
import com.qk.entity.OperateLog;
import com.qk.exception.BusinessException;
import com.qk.management.config.UserThreadLocal;
import com.qk.management.mapper.OperateLogMapper;
import com.qk.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author:zhengbowen
 * @Date: 2025/10/17 17:29
 * @Description: 日志切面
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class LogRecordAspect {

    private final OperateLogMapper operateLogMapper;


    @Around("@annotation(com.qk.management.annotation.LogAnno)")
    public Object logAround(ProceedingJoinPoint joinPoint){
        Object resultValue = null;
        long startTime = System.currentTimeMillis();
        try {
            resultValue= joinPoint.proceed();
            long endTime = System.currentTimeMillis();
            OperateLog operateLog = OperateLog.builder()
                    .operateUserId(UserThreadLocal.getUser().getId())
                    .operateTime(LocalDateTime.now())
                    .className(joinPoint.getTarget().toString())
                    .methodName(joinPoint.getSignature().getName())
                    .methodParams(JSONUtil.toJsonStr(joinPoint.getArgs()))
                    .returnValue(JSONUtil.toJsonStr(joinPoint))
                    .costTime(Integer.parseInt(String.valueOf(endTime - startTime)))
                    .build();
            operateLogMapper.insert(operateLog);
        } catch (Throwable e) {
            Result.error(BusinessEnum.BUSINESS_ERROR);
            log.info("操作失败");
        }
        return resultValue;
    }
}
